package br.com.foxinline.manager.criar;

import br.com.foxinline.modelo.Usuario;
import br.com.foxinline.servico.GrupoServico;
import br.com.foxinline.servico.UsuarioServico;
import java.io.IOException;
import java.io.Serializable;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author roniere
 */
@ManagedBean
@SessionScoped
public class ManagerLayout implements Serializable {

    @EJB
    UsuarioServico usuarioServico;
    @EJB
    GrupoServico grupoServico;
    private String user;
    private Usuario usuarioLogado;

    @PostConstruct
    public void init() {
        Principal userPrincipal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();


        usuarioLogado = usuarioServico.getCurrentUser();

        if (userPrincipal != null) {
            String userPrincipalName = userPrincipal.getName();

            this.user = usuarioServico.getNomeUsuario(userPrincipalName);
            String[] nome = this.user.trim().split(" ");
            if (nome.length > 1) {
                this.user = nome[0];
            }
        }
    }

    public void logout() throws IOException {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.responseComplete();
        facesContext.getExternalContext().invalidateSession();
        facesContext.getExternalContext().redirect("/Paracelsus-war/login.jsp");
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getMes() {
        GregorianCalendar g = new GregorianCalendar();
        g.setTime(new Date());

        return new SimpleDateFormat("MMM", new Locale("pt", "br")).format(g.getTime());
    }

    public String getAno() {
        GregorianCalendar g = new GregorianCalendar();
        g.setTime(new Date());

        return new SimpleDateFormat("yyyy", new Locale("pt", "br")).format(g.getTime());
    }

    /**
     * Verifica se o usuário logado é admin do sistema
     *
     * @return
     */
    public boolean isAdmin() {
        return usuarioServico.isAdmin();
    }

    public Usuario getUsuarioLogado() {
        return usuarioLogado;
    }

    public void setUsuarioLogado(Usuario usuarioLogado) {
        this.usuarioLogado = usuarioLogado;
    }
}
